<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\PlatformAccountBook;
use vm\com\BaseModel;
use vm\com\BaseService;

class PlatformAccountBookService extends BaseService
{

    /**
     * @return PlatformAccountBook
     */
    protected function getModel()
    {
        return new PlatformAccountBook();
    }

    /**
     * @return PlatformAccountService
     */
    private function getPlatformAccountService()
    {
        return service('PlatformAccount', SERVICE_NAMESPACE);
    }

    public function create(array $data)
    {
        $data['dateline'] = time();
        $result = parent::create($data);
        return $result;
    }

    /**
     * 记录收支
     * @param int $type     类型，具体查看 PlatformAccountBook::TYPE_*
     * @param float $money    金额
     * @param null $iidType 第三方id类型，具体查看 PlatformAccountBook::IID_TYPE_*
     * @param string $iid   第三方id
     * @param mixed|null $extend    扩展数据
     * @param string $remark        备注
     * @return int
     * @throws Exception
     */
    public function record($type, $money, $iidType = null, $iid = '', $extend = null, $remark = '')
    {
        $platformAccount = $this->getPlatformAccountService()->info(['keyname' => 'platform']);
        $data = [
            'type' => $type,
            'money' => $money,
            'remaining_money' => $platformAccount['remaining_money'],
            'remark' => $remark
        ];
        if($iidType !== null) {
            $data['iid_type'] = $iidType;
            $data['iid'] = $iid;
        }
        if($extend) {
            $data['extend'] = is_array($extend) || is_object($extend) ? json_encode($extend) : $extend;
        }
        return $this->create($data);
    }

    public function sum($field, array $params = [])
    {
        $model = $this->getModel();
        foreach ($params as $key => $val) {
            if(is_array($val)) {
                $model = $model->where($key, $val[0], $val[1]);
            } else if($key == 'min_time') {
                $model = $model->where('dateline', '>=', $val);
            } else if($key == 'max_time') {
                $model = $model->where('dateline', '<=', $val);
            } else {
                $model = $model->where($key, $val);
            }
        }
        return $model->sum($field);
    }
}